/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package com.dc.gameserver.extComponents.Kit.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Map转换为Object对象
 */
public class Map2Object {
	
	public final static SimpleDateFormat DATEFORMAT_SEC = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 通过反射，注入model属性
     * @param map
     * @param classType
     * @return  Object
     */
    @SuppressWarnings("unchecked")
	public static Object run2Object(Map<String, String> map,Class classType){
		Object objectCopy = null;
		try {
			objectCopy = classType.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		// 获得对象的所有属性
        Field[] fields = classType.getDeclaredFields();

		for (Field field : fields) {
			// 获取数组中对应的属性
			String fieldName = field.getName();
			String stringLetter = fieldName.substring(0, 1).toUpperCase();

			// 获得相应属性的setXXX方法名称
			String setName = "set" + stringLetter + fieldName.substring(1);


			// 获取相应的setXXX方法
			Method setMethod = null;
			try {
				setMethod = classType.getMethod(setName, new Class[] {field
						.getType()});
			} catch (Exception e) {
				continue;
			} 

			// 调用拷贝对象的setXXX方法
			try {
				Class classes[]  = setMethod.getParameterTypes();
				Object value = null;
				String fieldValue = map.get(fieldName);
				if(fieldValue == null || "".equals(fieldValue)){
					
				}else if(classes[0].equals(Date.class)){
					value = DATEFORMAT_SEC.parse(fieldValue);
				}else if(classes[0].equals(Integer.class)){
					value = Integer.valueOf(fieldValue);
				}else if(classes[0].equals(Long.class)){
					value = Long.valueOf(fieldValue);
				}else if(classes[0].equals(Float.class)){
					value = Float.valueOf(fieldValue);
				}else if(classes[0].equals(Double.class)){
					value = Double.valueOf(fieldValue);
				}else
					value = fieldValue;
				setMethod.invoke(objectCopy, value);
			} catch (Exception ignored) {
            }

		}
		return objectCopy;
	}

}
